# -*- coding: utf-8 -*-
"""
Tencent is pleased to support the open source community by making 蓝鲸智云PaaS平台社区版 (BlueKing PaaS Community
Edition) available.
Copyright (C) 2017 THL A29 Limited, a Tencent company. All rights reserved.
Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://opensource.org/licenses/MIT
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
specific language governing permissions and limitations under the License.
"""

from django.http import JsonResponse
from blueking.component.shortcuts import get_client_by_request
from django.shortcuts import render
import time
import json
from .constants import JOB_BK_BIZ_ID,MAX_ATTEMPTS,SEARCH_FILE_PLAN_ID,BACKUP_FILE_PLAN_ID,BK_JOB_HOST,WAITING_CODE,SUCCESS_CODE,WEB_SUCCESS_CODE,JOB_RESULT_ATTEMPTS_INTERVAL
from .models import BackupRecord  # 确保导入模型

def get_bizs_list(request):
    try:
        client = get_client_by_request(request)
        kwargs = {
            "fields": ["bk_biz_id", "bk_biz_name"],
            "page": {
                "start": 0,
                "limit": 10,
                "sort": ""
            }
        }
        response = client.cc.search_business(kwargs)
        return JsonResponse(response)
    except Exception as e:
        return JsonResponse({"result": False, "bk_error_msg": str(e)})

def get_sets_list(request):
    """
    根据业务ID，查询业务下的集群列表
    """
    try:
        bk_biz_id = request.GET.get("bk_biz_id")
        if bk_biz_id is None:
            return JsonResponse({"result": False, "bk_error_msg": "bk_biz_id is required"})

        client = get_client_by_request(request)
        kwargs = {
            "bk_biz_id": bk_biz_id,  # 使用已获取的参数
            "fields": ["bk_set_id", "bk_set_name", "bk_biz_id",
                       "bk_created_at", "bk_supplier_account"],
        }
        result = client.cc.search_set(kwargs)
        return JsonResponse(result)
    except Exception as e:
        return JsonResponse({"result": False, "bk_error_msg": str(e)})

def get_modules_list(request):
    try:
        client = get_client_by_request(request)
        kwargs = {
            "bk_biz_id": request.GET.get('bk_biz_id'),
            "bk_set_id": request.GET.get("bk_set_id"),
            "fields": ["bk_module_id", "bk_module_name", "bk_set_id", "bk_biz_id", "bk_created_at", "bk_supplier_account"]
        }
        response = client.cc.search_module(kwargs)
        return JsonResponse(response)
    except Exception as e:
        return JsonResponse({"result": False, "bk_error_msg": str(e)})

def get_hosts_list(request):
    try:
        client = get_client_by_request(request)
        kwargs = {
            "bk_biz_id": request.GET.get('bk_biz_id'),
            "page": {"start": 0, "limit": 100, },
            "fields": ["bk_host_id", "bk_cloud_id", "bk_host_innerip", "bk_os_type", "bk_mac", "operator",
                       "bk_bak_operator"]
        }
        if request.GET.get("bk_set_id"):
            kwargs["bk_set_ids"] = [int(request.GET.get("bk_set_id"))]
        if request.GET.get("bk_module_id"):
            kwargs["bk_module_ids"] = [int(request.GET.get("bk_module_id"))]
        rules = []
        if request.GET.get("operator"):
            rules.append({
                "field": "operator",
                "operator": "equal",
                "value": request.GET.get("operator")

            })
        if rules:
            kwargs["host_property_filter"] = {
                "condition": "AND",
                "rules": rules
            }
        response = client.cc.list_biz_hosts(kwargs)
        return JsonResponse(response)
    except Exception as e:
        return JsonResponse({"result": False, "bk_error_msg": str(e)})

def get_host_detail(request):
    try:
        client = get_client_by_request(request)
        kwargs = {
            "bk_host_id": request.GET.get('bk_host_id')
        }
        response = client.cc.get_host_base_info(kwargs)
        return JsonResponse(response)
    except Exception as e:
        return JsonResponse({"result": False, "bk_error_msg": str(e)})

def get_backup_record(request):
    """
    查询备份记录
    """
    try:
        res_data = {
            "result": True,
            "data": list(BackupRecord.objects.all().order_by("id").values()),
            "code": WEB_SUCCESS_CODE,
        }
        return JsonResponse(res_data)
    except Exception as e:
        return JsonResponse({"result": False, "bk_error_msg": str(e)})

def search_file(request):
    """
    根据主机IP、文件目录和文件后缀，查询符合条件的主机文件
    """
    try:
        # 注意：先在 constants.py 中替换 SEARCH_FILE_PLAN_ID 为你自己在作业平台上新建的方案的 ID
        host_id_list_str = request.GET.get("host_id_list")
        host_id_list = [int(bk_host_id) for bk_host_id in host_id_list_str.split(",")]
        kwargs = {
            "bk_scope_type": "biz",
            "bk_scope_id": JOB_BK_BIZ_ID,
            "job_plan_id": SEARCH_FILE_PLAN_ID,
            "global_var_list": [
                {
                    "name": "host_list",
                    "server": {
                        "host_id_list": host_id_list,
                    },
                },
                {
                    "name": "search_path",
                    "value": request.GET.get("search_path"),
                },
                {
                    "name": "suffix",
                    "value": request.GET.get("suffix"),
                },
            ],
        }
        # 调用执行方案
        client = get_client_by_request(request)
        job_instance_id = client.jobv3.execute_job_plan(**kwargs).get("data").get("job_instance_id")
        kwargs = {
            "bk_scope_type": "biz",
            "bk_scope_id": JOB_BK_BIZ_ID,
            "job_instance_id": job_instance_id,
        }
        attempts = 0
        while attempts < MAX_ATTEMPTS:
            # 获取执行方案执行状态
            step_instance_list = client.jobv3.get_job_instance_status(**kwargs).get("data").get("step_instance_list")
            if step_instance_list[0].get("status") == WAITING_CODE:
                time.sleep(JOB_RESULT_ATTEMPTS_INTERVAL)
            elif step_instance_list[0].get("status") != SUCCESS_CODE:
                res_data = {
                    "result": False,
                    "code": WEB_SUCCESS_CODE,
                    "message": "search failed",
                }
                return JsonResponse(res_data)
            elif step_instance_list[0].get("status") == SUCCESS_CODE:
                break
            attempts += 1

        step_instance_id = step_instance_list[0].get("step_instance_id")

        log_list = []
        for bk_host_id in host_id_list:
            data = {
                "bk_scope_type": "biz",
                "bk_scope_id": JOB_BK_BIZ_ID,
                "job_instance_id": job_instance_id,
                "step_instance_id": step_instance_id,
                "bk_host_id": bk_host_id,
            }
            # 查询执行日志
            response = client.jobv3.get_job_instance_ip_log(**data).get("data")
            step_res = response.get("log_content")
            json_step_res = json.loads(step_res)
            json_step_res["bk_host_id"] = response.get("bk_host_id")
            log_list.append(json_step_res)
        res_data = {
            "result": True,
            "code": WEB_SUCCESS_CODE,
            "data": log_list,
        }
        return JsonResponse(res_data)
    except Exception as e:
        return JsonResponse({"result": False, "bk_error_msg": str(e)})

def backup_file(request):
    """
    根据主机IP、文件目录和文件后缀，备份符合条件的主机文件到指定目录
    """
    try:
        # 注意：先在 constants.py 中替换 BACKUP_FILE_PLAN_ID 为你自己在作业平台上新建的方案的 ID
        host_id_list_str = request.GET.get("host_id_list")
        host_id_list = [int(bk_host_id) for bk_host_id in host_id_list_str.split(",")]
        search_path = request.GET.get("search_path")
        suffix = request.GET.get("suffix")
        kwargs = {
            "bk_scope_type": "biz",
            "bk_scope_id": JOB_BK_BIZ_ID,
            "job_plan_id": BACKUP_FILE_PLAN_ID,
            "global_var_list": [
                {
                    "name": "host_list",
                    "server": {
                        "host_id_list": host_id_list,
                    },
                },
                {
                    "name": "search_path",
                    "value": search_path
                },
                {
                    "name": "suffix",
                    "value": suffix
                },
                {
                    "name": "backup_path",
                    "value": request.GET.get("backup_path"),
                },
            ],
        }
        # 调用执行方案
        client = get_client_by_request(request)
        job_instance_id = client.jobv3.execute_job_plan(**kwargs).get("data").get("job_instance_id")
        kwargs = {
            "bk_scope_type": "biz",
            "bk_scope_id": JOB_BK_BIZ_ID,
            "job_instance_id": job_instance_id,
        }
        attempts = 0
        while attempts < MAX_ATTEMPTS:
            # 获取执行方案执行状态
            step_instance_list = client.jobv3.get_job_instance_status(**kwargs).get("data").get("step_instance_list")
            if step_instance_list[0].get("status") == WAITING_CODE:
                time.sleep(JOB_RESULT_ATTEMPTS_INTERVAL)
            elif step_instance_list[0].get("status") != SUCCESS_CODE:
                res_data = {
                    "result": False,
                    "code": WEB_SUCCESS_CODE,
                    "message": "backup failed",
                }
                return JsonResponse(res_data)
            elif step_instance_list[0].get("status") == SUCCESS_CODE:
                break
            attempts += 1
        step_instance_id = step_instance_list[0].get("step_instance_id")
        for bk_host_id in host_id_list:
            data = {
                "bk_scope_type": "biz",
                "bk_scope_id": JOB_BK_BIZ_ID,
                "job_instance_id": job_instance_id,
                "step_instance_id": step_instance_id,
                "bk_host_id": bk_host_id,
            }
            # 查询执行日志
            response = client.jobv3.get_job_instance_ip_log(**data).get("data")
            step_res = response.get("log_content")
            json_step_res = json.loads(step_res)
            for step_res in json_step_res:
                # 创建备份记录
                step_res["bk_host_id"] = bk_host_id
                step_res["bk_file_dir"] = search_path
                step_res["bk_file_suffix"] = suffix
                step_res["bk_file_operator"] = request.user.username
                step_res["bk_job_link"] = "{}/biz/{}/execute/task/{}".format(
                    BK_JOB_HOST,
                    JOB_BK_BIZ_ID,
                    job_instance_id,
                )
                BackupRecord.objects.create(**step_res)
        res_data = {
            "result": True,
            "data": "success",
            "code": WEB_SUCCESS_CODE,
        }
        return JsonResponse(res_data)
    except Exception as e:
        return JsonResponse({"result": False, "bk_error_msg": str(e)})